﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using SGLLv2.UI.Properties;

namespace SGLLv2.UI
{
    public partial class FormMessenger : Template.FormSCRUDTemplate, IMethods
    {
        // Declare Global Variables
        private MDIParent mdiParent;

        // Class Constructor
        public FormMessenger()
        {
            InitializeComponent();

            // Initialize Number of Required Controls.
            NumberOfAlterationsToSave = 4;
        }

        // Form
        private void FormMessenger_Load(object sender, EventArgs e)
        {
            // Declare Local Variables
            mdiParent = (MDIParent)(ParentForm);
            if (mdiParent == null) return;

            try
            {
                // Validate
                var value = queriesTableAdapter.IsAnyAllMessengersLocked(true);
                value = value.HasValue ? value.Value : 0;
                if (value > 0)
                {
                    // Let the user know what's going on.
                    mdiParent.SetMessage(MDIParent.MessageType.Warning, string.Format(Resources.MessageWarningStillLockedMessengers, value));

                    // Add Lambda Expression to close the form immediately.
                    Shown += (o, args) => Dispose();
                    
                    // Exit Form
                    return;
                }

                // Lock Every Messenger on table.
                queriesTableAdapter.UpdateLockOnAllMessengers(true, DateTime.Now, Environment.UserName, Environment.MachineName);

                // Fill out each dataset.
                sP_MESSENGERS_SELECTTableAdapter.Fill(dataSetSGLL.SP_MESSENGERS_SELECT);
                sP_USERS_SELECTTableAdapter.Fill(dataSetSGLL.SP_USERS_SELECT);

                // Clear form
                ClearForm();

                // Removed preselected Filter ComboBoxes.
                comboBoxMessenger.SelectedIndex = -1;

                // Prevent from calling future times the Call Form
                mdiParent.toolStripMenuItemMessengers.Enabled = false;

                // Hooking Up Events
                dataGridView.RowEnter += DataGridView_OnRowEnter;
                comboBoxMessenger.SelectedIndexChanged += comboBoxMessenger_SelectedIndexChanged;
            }
            catch (Exception exception)
            {
                // Report Error
                mdiParent.SetMessage(MDIParent.MessageType.Error, exception.Message);
                Utilities.ExceptionManager(exception);
            }
        }
        private void FormMessenger_FormClosing(object sender, FormClosingEventArgs e)
        {
            // If still editing prompt the user for decision.
            if (IsEditing && mdiParent.SetMessage(MDIParent.MessageType.Question, Resources.MessageWarningStillPendingChanges).Equals(DialogResult.Cancel))
                e.Cancel = true;

            // Release Every Messenger on table.
            queriesTableAdapter.UpdateLockOnAllMessengers(false, null, null, null);
        }

        // Data Grid View
        private void DataGridView_OnRowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // Validation
            if (dataGridView.CurrentRow == null) return;

            // Prevent Unwanted Changes
            if (ModifiedItems() > 0 && !IsEditing && MessageBox.Show(Resources.MessagePreventDataLoss, Global.AppFullName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3).Equals(DialogResult.No))
                return;

            // Coding
            labelIDValue.Text = dataGridView[códigoDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            comboBoxMessenger.Text = dataGridView[mensajeroDataGridViewTextBoxColumn.Index, e.RowIndex].Value.ToString();
            numericUpDownDepositReceipt.Value = Convert.ToDecimal(dataGridView[reciboDeIngresoDataGridViewTextBoxColumn.Index, e.RowIndex].Value);
            numericUpDownProofOfPayment.Value = Convert.ToDecimal(dataGridView[comprobanteDePagoDataGridViewTextBoxColumn.Index, e.RowIndex].Value);
            numericUpDownProcessOrder.Value = Convert.ToDecimal(dataGridView[ordenDeProcesoDataGridViewTextBoxColumn.Index, e.RowIndex].Value);

            // Setting Exists Variable
            IsEditing = true;
        }
        private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            // Clear any selection on the Data Grid View.
            dataGridView.ClearSelection();
        }

        // Numeric Up Down
        private void numericUpDowns_ValueChanged(object sender, EventArgs e)
        {
            // Enable Logic
            var numericUpDown = (NumericUpDown) sender;

            if (numericUpDown.Value.Equals(numericUpDown.Minimum))
                Remove(numericUpDown.Name);
            else
                Add(numericUpDown.Name);
        }
        private void numericUpDown_Enter(object sender, EventArgs e)
        {
            var numericUpDown = (NumericUpDown)sender;
            numericUpDown.Select(0, numericUpDown.Text.Length);
        }

        // Combo Box
        void comboBoxMessenger_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Enable Logic
            if (comboBoxMessenger.SelectedIndex.Equals(-1))
                Remove(comboBoxMessenger.Name);
            else
                Add(comboBoxMessenger.Name);
        }
        private void comboBoxMessenger_KeyDown(object sender, KeyEventArgs e)
        {
            // Validate if is the Delete Key.
            if (!e.KeyCode.Equals(Keys.Delete)) return;

            // Clear any selection on the ComboBox.
            comboBoxMessenger.SelectedIndex = -1;
            Remove(comboBoxMessenger.Name);
        }

        // Interface
        public void New()
        {
        }
        public void Save()
        {
            try
            {
                // Begin
                mdiParent.Begin();

                // Coding
                mdiParent.toolStripButtonSave.Enabled = false;
                queriesTableAdapter.InsertUpdateMessengers(IsEditing, labelIDValue.Text, comboBoxMessenger.Text, Convert.ToInt32(numericUpDownDepositReceipt.Value), Convert.ToInt32(numericUpDownProofOfPayment.Value), Convert.ToInt32(numericUpDownProcessOrder.Value), Environment.UserName, Environment.MachineName);

                // Let the user know what's going on.
                mdiParent.SetMessage(MDIParent.MessageType.Successful, IsEditing ? Resources.MessageSuccessfulUpdateMessager : Resources.MessageSuccessfulInsertMessager);

                // Clear form
                ClearForm();
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End
                mdiParent.End();
            }
        }
        public void Print()
        {
        }
        public void SetControlBox()
        {
            // Toolbar button
            mdiParent.toolStripMenuItemClear.Enabled = mdiParent.toolStripButtonClear.Enabled = true;
            //mdiParent.toolStripMenuItemNew.Enabled = mdiParent.toolStripButtonNew.Enabled = true;

            //EnableButtonSave();

            // Status bar
            //mdiParent.toolStripStatusLabelShowAllCalls.Visible = mdiParent.toolStripStatusLabelNumberCallsFiltered.Visible = true;

            // Hooking up the binding source.
            //mdiParent.toolStripMenu.BindingSource = sPCALLSSELECTBindingSource;
        }
        public void ClearFilter()
        {
            // Reset each control

            // Call method
            RefreshMessengers();
        }
        public void ClearForm()
        {
            // Variables
            IsEditing = false;

            // Data Grid View
            dataGridView.ClearSelection();

            // Set the next Call ID
            labelIDValue.Text = Convert.ToString(queriesTableAdapter.GetNextIDMessenger());

            // Clear selection on Combo Boxes.
            comboBoxMessenger.SelectedIndex = -1;

            // Clear Numeric Up Down.
            numericUpDownDepositReceipt.Value = numericUpDownDepositReceipt.Minimum;
            numericUpDownProcessOrder.Value = numericUpDownProcessOrder.Minimum;
            numericUpDownProofOfPayment.Value = numericUpDownProofOfPayment.Minimum;

            // Reload Grid
            RefreshMessengers();

            // Set Focus
            comboBoxMessenger.Focus();

            // Reset Status Bar
            mdiParent.SetMessage();
        }
        public void ChangeFormView(Global.FormViewModes mode)
        {

        }
        public void EnablePrintButton()
        {

        }
        public void Export()
        {
        }

        // General Purpose Functions
        private void RefreshMessengers()
        {
            try
            {
                // Start process
                mdiParent.Begin();

                // Fill Table Adapter
                sP_MESSENGERS_SELECTTableAdapter.Fill(dataSetSGLL.SP_MESSENGERS_SELECT);
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End process
                mdiParent.End();
            }
        }
        protected override void OnSaveReady(EventArgs e)
        {
            base.OnSaveReady(e);
            mdiParent.ChangeStatusSaveButton(true);
        }
        protected override void OnSaveWaiting(EventArgs e)
        {
            base.OnSaveWaiting(e);
            mdiParent.ChangeStatusSaveButton(false);
        }
    }
}